package cn.drenal.capcap.controller.forum;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.drenal.capcap.common.Response;
import cn.drenal.capcap.entity.Activity;
import cn.drenal.capcap.entity.vo.forum.ForumActivityDetailVO;
import cn.drenal.capcap.entity.vo.forum.ForumActivityVO;
import cn.drenal.capcap.service.ActivityService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 前台活动控制器
 */
@RestController
@RequestMapping("/forum/activity")
@RequiredArgsConstructor
public class ForumActivityController {

    private final ActivityService activityService;

    /**
     * 获取活动列表
     *
     * @param status 活动状态：null-全部，0-投稿期，1-公示期，2-投票期
     * @return 活动列表
     */
    @SaIgnore
    @GetMapping("/list")
    public Response<List<ForumActivityVO>> getActivityList(@RequestParam(required = false) Integer status) {
        // 构建查询条件
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果状态不为空，则按状态筛选
        if (status != null) {
            queryWrapper.eq(Activity::getStatus, status);
        }
        
        // 按开始时间倒序排序
        queryWrapper.orderByDesc(Activity::getStartTime);
        
        // 查询活动列表
        List<Activity> activityList = activityService.list(queryWrapper);
        
        // 转换为VO对象
        List<ForumActivityVO> voList = activityList.stream().map(activity -> {
            ForumActivityVO vo = new ForumActivityVO();
            BeanUtils.copyProperties(activity, vo);
            vo.setTitle(activity.getName()); // 名称映射到标题
            return vo;
        }).collect(Collectors.toList());
        
        return Response.success(voList);
    }

    /**
     * 获取活动详情
     *
     * @param id 活动ID
     * @return 活动详情
     */
    @SaIgnore
    @GetMapping("/{id}")
    public Response<ForumActivityDetailVO> getActivityDetail(@PathVariable Long id) {
        // 增加访问量并获取活动详情
        ForumActivityDetailVO activity = activityService.incrementViewCountAndGet(id);
        if (activity == null) {
            return Response.error("活动不存在");
        }
        return Response.success(activity);
    }
}